<template>
  <div>
    <!-- <div class="Login_hd">
      <div class="Login_logo">
        <img :src="corpLogo" />
      </div>
      <ul class="hotline">
        <li v-for="(item,i) in imglistone" :key="i">
          <span>
            <img :src="item.loginRightImg" />
          </span>
          <span>{{item.loginRightNote}}</span>
        </li>
      </ul>
    </div>-->
    <div class="logincontent" :style="{ 'background-image': 'url(' + this.corpFaceImg + ')' }">
      <!-- <div class="LoginImg">
        <div class="login-left-img">
          <img src="../../assets/images/login/login_01.png" />
        </div>
      </div>-->
      <div class="LoginBox">
        <div class="titleinfo" v-if="flag4">{{ titleinfo }}</div>
        <div class="vip-login-cont">
          <div class="ture-line-login">
            <div class="vip-login-t">
              <!-- <h2 style="text-align:left;width:300px;">如有账号，请登录</h2> -->

              <!-- <h2 @click="gologin()">如有账号登录</h2> -->
              <h2 class="text-align:left;color:#ccc" @click="restpassword()">忘记密码？</h2>
              <p class="mianreg">


                <span class="yuanxing">></span>
                <span class="reg" style=" color: #df0615; font-size: 13px;">
                  <span @click="gologin()" v-if="flagaddshop">账号登录入口</span>
                  <span @click="addshop()" v-if="flagdeng">新开店铺申请入口</span>
                </span>
              </p>
            </div>
            <div class="viplogo">
              <!-- <h2 style="text-align:left;width:300px;">如有账号，请登录</h2> -->
              <img src="../../assets/images/login/logo.png" style="margin: 0px 0px 15px 0;" />
            </div>
            <el-form :model="loginForm" :rules="rules" ref="loginForm">
              <template v-if="flagdeng">
                <el-form-item prop="username">
                  <span class="suoren"></span>
                  <!-- <el-input
                    type="password"
                    placeholder="请输入用户名"
                    v-model="username"
                    style="position:fixed;bottom:-9999px;"
                  >
                    <i
                      slot="prefix"
                      style="font-size: 17px;line-height: 32px;"
                      class="el-input__icon el-icon-lock"
                    ></i>
                  </el-input>-->
                  <el-input v-model="loginForm.username" placeholder="请输入用户名/门店授权编码" style="width: 65%;height:40px"
                    @keyup.enter.native="submitForm()">
                    <i slot="prefix" class="el-input__icon el-icon-s-custom"
                      style="font-size: 17px;line-height: 32px;"></i>
                  </el-input>
                </el-form-item>
                <el-form-item prop="password">
                  <span class="suoren"></span>
                  <!-- <el-input
                    type="password"
                    placeholder="请输入密码"
                    v-model="password"
                    style="position:fixed;bottom:-9999px"
                  >
                    <i
                      slot="prefix"
                      style="font-size: 17px;line-height: 32px;"
                      class="el-input__icon el-icon-lock"
                    ></i>
                  </el-input>-->
                  <el-input type="password" placeholder="请输入密码" style="width: 65%;height:40px"
                    v-model="loginForm.password" @keyup.enter.native="submitForm()" :disabled="flag6">
                    <i slot="prefix" style="font-size: 17px;line-height: 32px;" class="el-input__icon el-icon-lock"></i>
                  </el-input>
                </el-form-item>
                <el-form-item prop="imageCode">
                  <span class="suoren"></span>
                  <div class="code-wrap">
                    <div class="code-wrap-box">
                      <el-input style="width: 50%;height:40px" maxlength="4" v-model="loginForm.imageCode"
                        placeholder="请输入验证码" @keyup.enter.native="submitForm()" />
                      <img class="code-num" @click.prevent="changeImgCode()" :src="imageCodeUrl" />
                    </div>
                  </div>
                </el-form-item>
              </template>

              <el-form-item prop="authCode" v-if="flagaddshop">
                <span class="suoren"></span>
                <el-input placeholder="请输入店铺授权编码" style="  width: 60%;height:40px"
                  @input="confirmCode" maxlength="12" v-model="loginForm.authCode"
                  @keyup.enter.native="goshenqing()">
                  <i slot="prefix" style="font-size: 17px;line-height: 32px;" class="el-input__icon el-icon-lock"></i>
                </el-input>
                <!-- <div style="font-size:12px;color:#ccc">（请输入五粮液CRM系统的专卖店授权码）</div> -->
              </el-form-item>
              <!-- <el-form-item prop="verifycode" v-if="flag3" style="position:relative"> -->
              <!-- 注意：prop与input绑定的值一定要一致，否则验证规则中的value会报undefined，因为value即为绑定的input输入值 -->
              <!-- <el-input v-model="loginForm.verifycode" placeholder="请输入验证码" class="identifyinput">
                  <i class="el-input__icon el-icon-view" slot="suffix" style="font-size: 20px"></i>
                </el-input>
              <span v-if="flag7" class="errorinfo">验证码输入错误!</span>-->
              <!-- <span v-if="flag8" class="errorinfo">{{messageinfo}}</span> -->
              <!-- </el-form-item> -->
              <!-- <el-form-item v-if="flag3">
                <div class="identifybox">
                  <div @click="refreshCode">
                    <s-identify :identifyCode="identifyCode"></s-identify>
                  </div>
                  <el-button @click="refreshCode" type="text" class="textbtn">看不清，换一张</el-button>
                </div>
              </el-form-item>-->
              <!-- <div class="vip-login-t"> -->
              <!-- <h2>
                  <span class="duigou">√</span>自动登录
              </h2>-->
              <!-- <p class="mianreg">
                  <span
                    class="reg"
                    style=" color: #ff732e;
                   font-size: 13.5px;"
                  >忘记密码？</span>
                </p>
              </div>-->
              <el-form-item>
                <el-button type="primary" @click="submitForm('loginForm')" class="submit_btn"
                  v-if="flagdeng">登录</el-button>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="goshenqing('loginForm')" class="submit_btn"
                  v-if="flagaddshop">去申请</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
    </div>
    <!-- <div class="footer">
      <p style="line-height: 35px;">
        <span>关于我们</span>
        <span>|</span>
        <span>联系我们</span>
        <span>|</span>
        <span>加入我们</span>
        <span>|</span>
        <span>人才招聘</span>
        <span>|</span>
        <span>广告服务</span>
        <span>|</span>
        <span>友情链接</span>
    </p>-->
    <!-- <p class="banquan">
        版权所有
        <span id="corpName">北京中软国际信息技术有限公司</span>
        <br />Copyright ©
        <span id="corpWebsite">www.chinasofti.com</span> All Rights Reserved
    </p>-->
    <!-- </div> -->
  </div>
</template>

<script>
import { _login, logininfo, shopAuth, shopAuthdetail, getVerificationCode, getGenerateCookie } from "@/api/loginApi";
import SIdentify from "@/components/identify.vue";
import qs from "qs";

let timer;

export default {
  name: "CertificateLogin",
  data() {
    // 用户名自定义验证规则
    const validateUsername = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入正确的用户名"));
      } else {
        console.log("user", value);
        callback();
      }
    };
    // 验证码自定义验证规则
    const validateVerifycode = (rule, value, callback) => {
      let newVal = value.toLowerCase();
      let identifyStr = this.identifyCode.toLowerCase();
      if (newVal === "") {
        callback(new Error("请输入验证码"));
      } else if (newVal !== identifyStr) {
        console.log("validateVerifycode:", value);
        callback(new Error("验证码不正确!"));
      } else {
        callback();
      }
    };
    return {
      activeIndex: "1",
      dialogVisible: false,
      fontstyle: {
        color: "gray"
      },
      flagdeng: true,
      flagaddshop: false,
      count: 0,
      loginForm: {
        username: "",
        password: "",
        verifycode: "",
        authCode: "",
        imageCode: ""
      },
      username: "",
      password: "",
      corpLogo: require("../../assets/images/login/Login_logo.png"),
      corpLogochu: require("../../assets/images/login/login_02.png"),
      messageinfo: "",
      titleinfo: "",
      flag6: false,
      flag4: false,
      flag7: false,
      flag3: false,
      flag8: false,
      checked: false,
      corpFaceImg: require("../../assets/images/login/login_07.png"),
      chucorpFaceImg: "",
      identifyCodes: "1234567890ABCDEFGHIGKLMNoPQRSTUVWXYZ",
      identifyCode: "",
      //   loginRules: {
      //     // 绑定在form表单中的验证规则
      //     username: [
      //       { required: true, trigger: "blur", validator: validateUsername }
      //     ],
      //     password: [
      //       { required: true, message: "请输入密码", trigger: "blur" },
      //       { min: 6, message: "密码长度最少为6位", trigger: "blur" }
      //     ],
      //     verifycode: [
      //       { required: true, trigger: "blur", validator: validateVerifycode }
      //     ]
      //   },
      passwordType: "password",

      loginobj: {},

      datatenc: "",
      rules: {
        // username: [
        //   { required: true, message: "请输入用户名", trigger: "blur" }
        // ],
        // password: [{ required: true, message: "请输入密码", trigger: "blur" }]
      },
      imglistone: [],
      imglist: [
        {
          imgUrl: require("../../assets/images/login/login_03.png"),
          imgtext: "以我为主"
        },
        {
          imgUrl: require("../../assets/images/login/login_04.png"),
          imgtext: "管控有效"
        },
        {
          imgUrl: require("../../assets/images/login/login_05.png"),
          imgtext: "价值共享"
        },
        {
          imgUrl: require("../../assets/images/login/login_06.png"),
          imgtext: "多方共赢"
        }
      ],

      // 验证码
      randomCode: '',
      imageCodeUrl: '',
    };
  },
  components: {
    SIdentify
  },
  mounted() {
    // this.getlogininfo();
    this.identifyCode = "";
    this.makeCode(this.identifyCodes, 4);
    console.log(this.$route.query.tenc);
    localStorage.clear();
    // this.changeImgCode();
    this.createUUID();
  },
  filters: {
    checkChange(formName) {
      if (this.checked === true) {
        // this.loginForm.username = "admin";
        // this.loginForm.password = "111111";
        // this.loginForm.verifycode = "";
      } else {
        this.$nextTick(() => {
          this.$refs[formName].resetFields();
        });
      }
    }
  },
  props: [],
  methods: {
    restpassword() {
      this.$router.push("/restpassword");
    },
    getPhoto() { },
    // 通过改变input的type使密码可见
    showPassword() {
      this.fontstyle.color === "gray"
        ? (this.fontstyle.color = "blue")
        : (this.fontstyle.color = "gray"); // 改变密码可见按钮颜色
      this.passwordType === ""
        ? (this.passwordType = "password")
        : (this.passwordType = "");
    },
    // 点击登入按钮
    // handleLogin() {
    //   this.$refs.loginForm.validate(valid => {
    //     if (valid) {
    //       this.$router.push("/apply/Index");
    //     } else {
    //       this.$router.push("/apply/CertificateLogin");
    //     }
    //   });
    // },
    // 生成随机数
    randomNum(min, max) {
      return Math.floor(Math.random() * (max - min) + min);
    },
    // 切换验证码
    refreshCode() {
      this.identifyCode = "";
      this.makeCode(this.identifyCodes, 4);
    },
    // 生成四位随机验证码
    makeCode(o, l) {
      for (let i = 0; i < l; i++) {
        this.identifyCode += this.identifyCodes[
          this.randomNum(0, this.identifyCodes.length)
        ];
      }
      console.log(this.identifyCode);
    },
    applyFor() {
      this.dialogVisible = true;
    },
    handleClose(done) {
      done();
    },
    // handleLogin () {
    //   alert('登陆成功')
    //   this.dialogVisible = false
    // },
    handleSelect(key, keyPath) {
      console.log(key, keyPath);
    },
    addshop() {
      this.flagaddshop = true;
      this.flagdeng = false;
    },
    gologin() {
      this.flagaddshop = false;
      this.flagdeng = true;
    },

    submitForm() {
      // this.$router.push("manage");
      this.login();
    },
    goshenqing() {

      if (this.loginForm.authCode == "" || this.loginForm.authCode == null) {
        // this.$message.error("请输入密码");
        this.titleinfo = "请输入店铺授权编码"
        this.flag4 = true;

        clearTimeout(timer);
        timer = setTimeout(() => {
          this.flag4 = false;
        }, 2000);
        return;
      }
      let data = {
        authCode: this.loginForm.authCode
      };
      shopAuth(qs.stringify(data)).then(res => {
        this.titleinfo = res.message;
        this.flag4 = true;

        clearTimeout(timer);
        timer = setTimeout(() => {
          this.flag4 = false;
        }, 2000);
        if (res.code == 1) {
          //   this.$router.push("/addShopapply");
          localStorage.setItem("token", res.result.token);
          localStorage.setItem("authCode", this.loginForm.authCode);
          shopAuthdetail(data).then(res => {

            if (res.result.userReviewRecordList.length == 0) {
              let loginstatus = true;
              sessionStorage.setItem("loginstatus", loginstatus);

              this.$router.push({
                name: "addShopapply",
                params: {
                  v: res.result,
                  authCode: this.loginForm.authCode
                }
              });
            } else {
              let loginstatus = true;
              sessionStorage.setItem("loginstatus", loginstatus);
              this.$router.push({
                name: "applystep",
                params: {
                  v: res.result,
                  flagcode: true,
                  authCode: this.loginForm.authCode
                }
              });
            }
          });
        } else {
        }
      });
    },
    // getlogininfo() {
    //   console.log(this.$route.query.mt);
    //   this.$route.query.tenc
    //     ? (this.datatenc = this.$route.query.tenc)
    //     : (this.datatenc = "01");
    //   let data = { tenantCode: this.datatenc };
    //   logininfo(qs.stringify(data)).then(res => {
    //     //    console.log(res, "pp");
    //     res.result.tenantTitles.forEach((item, i) => {
    //       if (res.result.tenantTitles[i].loginRightImg == "") {
    //         this.imglistone = this.imglist;
    //       } else {
    //         this.imglistone = res.result.tenantTitles;
    //       }
    //     });

    //     res.result.corpLogo
    //       ? (this.corpLogo = res.result.corpLogo)
    //       : (this.corpLogo = this.corpLogochu);
    //     res.result.corpFaceImg
    //       ? (this.corpFaceImg = res.result.corpFaceImg)
    //       : (this.corpFaceImg = this.corpFaceImg);
    //   });
    // },
    login() {
      if (this.loginForm.username == "" || this.loginForm.username == null) {
        // this.$message.error("请输入用户名或手机号");
        this.titleinfo = "请输入用户名或门店授权编码"
        this.flag4 = true;

        clearTimeout(timer);
        timer = setTimeout(() => {
          this.flag4 = false;
        }, 2000);
        return;
      }
      if (this.loginForm.password == "" || this.loginForm.password == null) {
        // this.$message.error("请输入密码");
        this.titleinfo = "请输入密码"
        this.flag4 = true;

        clearTimeout(timer);
        timer = setTimeout(() => {
          this.flag4 = false;
        }, 2000);
        return;

      }
      if (this.loginForm.imageCode == "" || this.loginForm.imageCode == null) {
        this.titleinfo = "请输入验证码"
        this.flag4 = true;
        clearTimeout(timer);
        timer = setTimeout(() => {
          this.flag4 = false;
        }, 2000);
        return;
      }
      let data = {
        authId: this.loginForm.username,
        password: this.loginForm.password,
        imageCode: this.loginForm.imageCode,
        key: this.randomCode,
        authType: 1
        // tenantId: "01"
        // tenantId: this.datatenc
      };
      _login(qs.stringify(data)).then(res => {
        if (res.code == "1") {
          let loginstatus = true;
          sessionStorage.setItem("loginstatus", loginstatus);
          localStorage.setItem("token", res.result.token);
          localStorage.setItem("username", this.loginForm.username);
          localStorage.setItem(
            "URL",
            "http://49.4.27.95:8090/newRetailManageWeb/adSpace/adSpaceUI.html"
          );

          localStorage.setItem("userId", res.result.userId);
          this.loginobj = res.result;
          localStorage.setItem("logininfo", JSON.stringify(this.loginobj));
          //   this.$router.push("manage");
          this.$router.push({
            name: "manage",
            params: {
              tenantId: this.datatenc
            }
          });
        } else {
          this.count += 1;
          //   alert("账号密码错误请重新输入");
          if (this.count < 2) {
            this.titleinfo = res.message;
            this.flag4 = true;

            clearTimeout(timer);
            timer = setTimeout(() => {
              this.flag4 = false;
            }, 2000);
          }
          if (this.count < 5 && this.count >= 2) {
            this.titleinfo = res.message;
            this.flag4 = true;

            clearTimeout(timer);
            timer = setTimeout(() => {
              this.flag4 = false;
            }, 2000);
            this.flag3 = true;
          }
          if (this.count >= 5) {
            // alert("显示验证码");
            this.titleinfo = res.message;
            this.flag4 = true;

            clearTimeout(timer);
            timer = setTimeout(() => {
              this.flag4 = false;
            }, 3000);
          }
          //   if (this.count === 5) {
          //     this.flag7 = false;
          //     this.flag8 = true;
          //     this.messageinfo = res.message;
          //   }
          if (this.identifyCode === this.loginForm.verifycode) {
            if (this.count < 5) {
              this.flag7 = false;
              this.titleinfo = res.message;
              this.flag4 = true;
              clearTimeout(timer);
              timer = setTimeout(() => {
                this.flag4 = false;
              }, 3000);
            } else {
              this.flag7 = false;
              this.titleinfo = res.message;
              this.flag4 = true;
              clearTimeout(timer);
              timer = setTimeout(() => {
                this.flag4 = false;
              }, 3000);
            }

            localStorage.setItem("token", res.result.token);
            localStorage.setItem(
              "URL",
              "http://49.4.27.95:8090/newRetailManageWeb/adSpace/adSpaceUI.html"
            );
            localStorage.setItem("userId", res.result.userId);
            this.loginobj = res.result;
            localStorage.setItem("logininfo", JSON.stringify(this.loginobj));
            this.$router.push("manage");
          } else {
            this.flag7 = true;
            //   this.titleinfo = "验证码错误";
            //   this.flag4 = true;
            //   clearTimeout(timer)
            //   timer = setTimeout(() => {
            //     this.flag4 = false;
            //   }, 3000);
            // console.log("ooo");
            // alert("ll");
          }
          //   return false;

          this.changeImgCode();
        }
      });
    },
    // leaveverify() {
    //   if (this.loginForm.verifycode !== this.identifyCode) {
    //     console.log("iii");
    //     this.titleinfo = "验证码错误";
    //     this.flag4 = true;
    //     clearTimeout(timer)
    //     timer = setTimeout(() => {
    //       this.flag4 = false;
    //     }, 3000);
    //   }
    // }

    // 生成唯一标识
    createUUID() {
      getGenerateCookie().then(res => {
        if (res.code == 1) {
          if (!sessionStorage.getItem('SESSION')) {
            sessionStorage.setItem('SESSION', res.result);
          }
          this.changeImgCode();
        }
      })
    },

    // 获取验证码
    changeImgCode() {
      this.randomCode = sessionStorage.getItem('SESSION');
      getVerificationCode({
        key: this.randomCode
      }).then(res => {
        if (res.code == 1) {
          this.imageCodeUrl = `data:image/png;base64,${res.result}`;
        } else {
          this.$message.error(res.message);
        }
      })
    },

    // 验证授权码
    confirmCode() {
      this.loginForm.authCode=this.loginForm.authCode.replace(/[^\d\u4e00-\u9fa5]/g,'')
    }
  }
};
</script>

<style lang="less" scoped>
.logincontent {
  width: 100%;
  margin: 0px auto;
  // height: 520px;
  font-size: 12px;
  //   background-color: #e4393c;3

  background-size: 100% 520px;
  background-repeat: no-repeat;
  overflow: hidden;
  background-repeat: no-repeat;
}

@import "../../style/login";

.identifybox {
  display: flex;
  justify-content: space-between;
  margin-top: 7px;
}

.iconstyle {
  color: #409eff;
}

.titleinfo {
  width: 170px;
  height: 40px;
  background: #000;
  color: #fff;
  opacity: 0.4;
  font-size: 12px;
  position: absolute;
  top: 200px;
  text-align: center;
  line-height: 40px;
  z-index: 999;
  left: 195px;
}

.errorinfo {
  position: absolute;
  right: 8px;
  top: 36px;
  font-size: 12px;
  color: #fe732e;
}

.code-wrap {
  display: inline-block;
  width: 65%;

  .code-wrap-box {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .code-num {
    height: 40px;
    width: auto;
    cursor: pointer;
  }
}
</style>
